var http = require("../../../utils/https.js")
Page({

    /**
     * 页面的初始数据
     */
    data: {
      userInfo:{},
      balance: '0.00',
    },
    goToBillRecord() {
      wx.navigateTo({
        url: `/my/pages/billrecord/billrecord?userId=${this.data.userInfo.userId}`,
      })
    },
    goToRechargeRecord() {
        wx.navigateTo({
          url: `/my/pages/rechargerecord/rechargerecord?userId=${this.data.userInfo.userId}`,
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      var userInfo = wx.getStorageSync('userInfo')
      this.setData({
        userInfo:userInfo
      })
      if (!userInfo || !userInfo.userId) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        })
        wx.redirectTo({
          url: '/index/pages/mzhLogin/mzhLogin',
        })
        return
      }
      this.fetchBalance(userInfo.userId)
      
    },
    fetchBalance(userId){
      var that = this
      http.GET(`/balance/user/${userId}`, {}, function(res){
        if(res.code === 200){
          var obj = res.data || {}
          var val = obj.balance
          if(val === undefined || val === null){
            val = obj.amount
          }
          if(val === undefined || val === null){
            val = obj.total
          }
          if(val === undefined || val === null){
            val = obj.money
          }
          var num = 0
          if(typeof val === 'number'){
            num = val
          }else if(typeof val === 'string' && val.trim() !== ''){
            num = parseFloat(val)
            if(isNaN(num)) num = 0
          }
          that.setData({ balance: num.toFixed(2) })
        } else {
          that.handleAuthExpired(res)
        }
      }, function(err){
        console.error('余额获取失败:', err)
      })
    },
    onShow(){
      this.fetchBalance(this.data.userInfo.userId)
    },
    handleAuthExpired(res){
      wx.showToast({
        title: '认证过期，请重新登录',
        icon: 'none',
        duration: 1500
      })
      setTimeout(()=>{
        wx.redirectTo({
          url: '/index/pages/mzhLogin/mzhLogin',
        })
      }, 1500)
    },


})